/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.zzdt4j.adapter.web;

import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.StrUtil;
import cn.zzdt4j.common.model.ThreadPoolRunStateInfo;
import cn.zzdt4j.common.support.AbstractThreadPoolRuntime;
import cn.zzdt4j.common.toolkit.ByteConvertUtil;
import cn.zzdt4j.common.toolkit.MemoryUtil;

/**
 * Web thread pool run state handler.
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2023/10/26 2:25
 */
public class WebThreadPoolRunStateHandler extends AbstractThreadPoolRuntime {

    @Override
    public ThreadPoolRunStateInfo supplement(ThreadPoolRunStateInfo threadPoolRunStateInfo) {
        final long used = MemoryUtil.heapMemoryUsed();
        final long max = MemoryUtil.heapMemoryMax();
        final String memoryProportion = StrUtil.builder("Allocation",
                ByteConvertUtil.getPrintSize(used),
                " / Maximum available: ",
                ByteConvertUtil.getPrintSize(max)).toString();
        threadPoolRunStateInfo.setCurrentLoad(threadPoolRunStateInfo.getCurrentLoad() + "%");
        threadPoolRunStateInfo.setPeakLoad(threadPoolRunStateInfo.getPeakLoad() + "%");
        threadPoolRunStateInfo.setMemoryProportion(memoryProportion);
        threadPoolRunStateInfo.setFreeMemory(ByteConvertUtil.getPrintSize(Math.subtractExact(max, used)));
        return threadPoolRunStateInfo;
    }
}
